<script setup lang="tsx">
import { ref } from 'vue'
import { JsonEditor } from '@/components/JsonEditor'
import { ElDrawer, ElButton, ElMessage, ElInput } from 'element-plus'
import { useSetupFromOptionStoreWithOut } from '@/store/modules/setupFormOption'
import { FormSchema } from '@/components/Form'
import { propTypes } from '@/utils/propTypes'
import { convertToJSX, customStringify } from '../index'
import { cloneDeep } from 'lodash-es'
const setupStore = useSetupFromOptionStoreWithOut()
const props = defineProps({
  modelValue: Boolean,
  codeFrom: String,
  codeType: propTypes.oneOf(['search', 'detail', 'form', 'table', 'all']).def('search')
})
const emits = defineEmits(['update:modelValue', 'pasteFromClipboard'])
function onOpen() {
  if (props.codeType === 'search') {
    const code = setupStore.getSearchForm
    jsonData.value = code
  } else if (props.codeType === 'form') {
    const code = setupStore.getForm
    jsonData.value = code
  } else if (props.codeType === 'detail') {
    const code: any = setupStore.getDetailForm
    jsonData.value = cloneDeep(code)
  } else if (props.codeType === 'table') {
    const code: any = setupStore.getTable
    console.log(code)

    jsonData.value = cloneDeep(code)
  }
}

// 假设这是你的JSON数据（可以是对象或字符串）
const jsonData = ref<any>()

// 验证并复制函数
const validateAndCopy = async () => {
  try {
    if (['detail', 'table'].includes(props.codeType)) {
      jsonData.value.forEach((item) => {
        if (item.slots) {
          if (item.slots?.default) {
            const str = item.slots.default.toString().replace(/\n/g, '')
            item.slots.default = convertToJSX(str)
          }
          if (item.slots?.label) {
            const str = item.slots.label.toString().replace(/\n/g, '')
            item.slots.label = convertToJSX(str)
          }
        }
      })
    }
    // 步骤1: 验证JSON格式
    const jsonString =
      typeof jsonData.value === 'string' ? jsonData.value : JSON.stringify(jsonData.value)
    // 尝试解析以验证格式
    JSON.parse(jsonString)

    // 步骤2: 复制到剪贴板
    await copyToClipboard(jsonString)

    // 成功反馈
    ElMessage.success('JSON数据已成功复制到剪贴板！')
  } catch (error) {
    // 错误处理
    ElMessage.error('无效的 JSON 格式')
  }
}

// 复制到剪贴板的通用函数（兼容现代和旧版浏览器）
const copyToClipboard = (text) => {
  return new Promise<void>((resolve, reject) => {
    // 方法1: 使用现代 Clipboard API
    if (navigator.clipboard) {
      navigator.clipboard
        .writeText(text)
        .then(resolve)
        .catch((err) => {
          // 如果现代API失败，尝试回退方法
          fallbackCopy(text) ? resolve() : reject(err)
        })
    }
    // 方法2: 使用旧版execCommand
    else {
      fallbackCopy(text) ? resolve() : reject(new Error('复制失败'))
    }
  })
}

// 旧版浏览器的回退复制方法
const fallbackCopy = (text) => {
  try {
    // 创建临时textarea元素
    const textArea = document.createElement('textarea')
    textArea.value = text
    textArea.style.position = 'fixed'
    textArea.style.top = '0'
    textArea.style.left = '0'
    textArea.style.opacity = '0'

    // 添加到DOM
    document.body.appendChild(textArea)

    // 选中并复制
    textArea.focus()
    textArea.select()
    const successful = document.execCommand('copy')

    // 清理
    document.body.removeChild(textArea)

    return successful
  } catch (err) {
    console.error('回退复制失败:', err)
    return false
  }
}
// 验证输入是否为有效的JSON,并赋值
const validateJson = (jsonString) => {
  try {
    // 尝试解析JSON
    const parsed = JSON.parse(jsonString)
    jsonData.value = parsed
    if (['search'].includes(props.codeType)) {
      setupStore.setSearchForm(jsonData.value as FormSchema[])
    } else if (['form'].includes(props.codeType)) {
      setupStore.setForm(jsonData.value as FormSchema[])
    } else if (['detail'].includes(props.codeType)) {
      setupStore.setDetailForm(jsonData.value as any[])
    } else if (['table'].includes(props.codeType)) {
      setupStore.setTable(jsonData.value as any[])
    }
    emits('pasteFromClipboard')
    return true
  } catch (error) {
    // 显示错误消息
    ElMessage.error('无效的 JSON 格式')
    return false
  }
}
// 从剪贴板粘贴内容
const pasteFromClipboard = async () => {
  try {
    // 读取剪贴板内容
    const clipboardText = await navigator.clipboard.readText()

    // 验证JSON
    validateJson(clipboardText)
  } catch (error) {
    console.error('剪贴板访问失败:', error)
  }
}
</script>
<template>
  <ElDrawer
    :model-value="modelValue"
    @update:modelValue="$emit('update:modelValue', $event)"
    title="I am the title"
    :with-header="false"
    @open="onOpen"
  >
    <div class="flex justify-end">
      <ElButton type="primary" @click="pasteFromClipboard">粘贴 </ElButton>
      <ElButton type="primary" @click="validateAndCopy">复制 </ElButton>
    </div>
    <JsonEditor v-model="jsonData" />
  </ElDrawer>
</template>
